home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / tcl / tcl70b2.lha / tcl7.0b2 / tclUtil.c < prev    next >
C/C++ Source or Header  |  1993-06-19  |  50KB  |  1,888 lines

  1. /* 
  2.  * tclUtil.c --
  3.  *
  4.  *    This file contains utility procedures that are used by many Tcl
  5.  *    commands.
  6.  *
  7.  * Copyright (c) 1987-1993 The Regents of the University of California.
  8.  * All rights reserved.
  9.  *
  10.  * Permission is hereby granted, without written agreement and without
  11.  * license or royalty fees, to use, copy, modify, and distribute this
  12.  * software and its documentation for any purpose, provided that the
  13.  * above copyright notice and the following two paragraphs appear in
  14.  * all copies of this software.
  15.  * 
  16.  * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  17.  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  18.  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
  19.  * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  20.  *
  21.  * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  22.  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  23.  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  24.  * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
  25.  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  26.  */
  27.  
  28. #ifndef lint
  29. static char rcsid[] = "$Header: /user6/ouster/tcl/RCS/tclUtil.c,v 1.78 93/06/19 14:34:40 ouster Exp $ SPRITE (Berkeley)";
  30. #endif
  31.  
  32. #include "tclInt.h"
  33.  
  34. /*
  35.  * The following values are used in the flags returned by Tcl_ScanElement
  36.  * and used by Tcl_ConvertElement.  The value TCL_DONT_USE_BRACES is also
  37.  * defined in tcl.h;  make sure its value doesn't overlap with any of the
  38.  * values below.
  39.  *
  40.  * TCL_DONT_USE_BRACES -    1 means the string mustn't be enclosed in
  41.  *                braces (e.g. it contains unmatched braces,
  42.  *                or ends in a backslash character, or user
  43.  *                just doesn't want braces);  handle all
  44.  *                special characters by adding backslashes.
  45.  * USE_BRACES -            1 means the string contains a special
  46.  *                character that can be handled simply by
  47.  *                enclosing the entire argument in braces.
  48.  * BRACES_UNMATCHED -        1 means that braces aren't properly matched
  49.  *                in the argument.
  50.  */
  51.  
  52. #define USE_BRACES        2
  53. #define BRACES_UNMATCHED    4
  54.  
  55. /*
  56.  * The variable below is set to NULL before invoking regexp functions
  57.  * and checked after those functions.  If an error occurred then regerror
  58.  * will set the variable to point to a (static) error message.  This
  59.  * mechanism unfortunately does not support multi-threading, but then
  60.  * neither does the rest of the regexp facilities.
  61.  */
  62.  
  63. char *tclRegexpError = NULL;
  64.  
  65. /*
  66.  * Function prototypes for local procedures in this file:
  67.  */
  68.  
  69. static void        SetupAppendBuffer _ANSI_ARGS_((Interp *iPtr,
  70.                 int newSpace));
  71.  
  72. /*
  73.  *----------------------------------------------------------------------
  74.  *
  75.  * TclFindElement --
  76.  *
  77.  *    Given a pointer into a Tcl list, locate the first (or next)
  78.  *    element in the list.
  79.  *
  80.  * Results:
  81.  *    The return value is normally TCL_OK, which means that the
  82.  *    element was successfully located.  If TCL_ERROR is returned
  83.  *    it means that list didn't have proper list structure;
  84.  *    interp->result contains a more detailed error message.
  85.  *
  86.  *    If TCL_OK is returned, then *elementPtr will be set to point
  87.  *    to the first element of list, and *nextPtr will be set to point
  88.  *    to the character just after any white space following the last
  89.  *    character that's part of the element.  If this is the last argument
  90.  *    in the list, then *nextPtr will point to the NULL character at the
  91.  *    end of list.  If sizePtr is non-NULL, *sizePtr is filled in with
  92.  *    the number of characters in the element.  If the element is in
  93.  *    braces, then *elementPtr will point to the character after the
  94.  *    opening brace and *sizePtr will not include either of the braces.
  95.  *    If there isn't an element in the list, *sizePtr will be zero, and
  96.  *    both *elementPtr and *termPtr will refer to the null character at
  97.  *    the end of list.  Note:  this procedure does NOT collapse backslash
  98.  *    sequences.
  99.  *
  100.  * Side effects:
  101.  *    None.
  102.  *
  103.  *----------------------------------------------------------------------
  104.  */
  105.  
  106. int
  107. TclFindElement(interp, list, elementPtr, nextPtr, sizePtr, bracePtr)
  108.     Tcl_Interp *interp;        /* Interpreter to use for error reporting. */
  109.     register char *list;    /* String containing Tcl list with zero
  110.                  * or more elements (possibly in braces). */
  111.     char **elementPtr;        /* Fill in with location of first significant
  112.                  * character in first element of list. */
  113.     char **nextPtr;        /* Fill in with location of character just
  114.                  * after all white space following end of
  115.                  * argument (i.e. next argument or end of
  116.                  * list). */
  117.     int *sizePtr;        /* If non-zero, fill in with size of
  118.                  * element. */
  119.     int *bracePtr;        /* If non-zero fill in with non-zero/zero
  120.                  * to indicate that arg was/wasn't
  121.                  * in braces. */
  122. {
  123.     register char *p;
  124.     int openBraces = 0;
  125.     int inQuotes = 0;
  126.     int size;
  127.  
  128.     /*
  129.      * Skim off leading white space and check for an opening brace or
  130.      * quote.   Note:  use of "isascii" below and elsewhere in this
  131.      * procedure is a temporary hack (7/27/90) because Mx uses characters
  132.      * with the high-order bit set for some things.  This should probably
  133.      * be changed back eventually, or all of Tcl should call isascii.
  134.      */
  135.  
  136.     while (isascii(*list) && isspace(*list)) {
  137.     list++;
  138.     }
  139.     if (*list == '{') {
  140.     openBraces = 1;
  141.     list++;
  142.     } else if (*list == '"') {
  143.     inQuotes = 1;
  144.     list++;
  145.     }
  146.     if (bracePtr != 0) {
  147.     *bracePtr = openBraces;
  148.     }
  149.     p = list;
  150.  
  151.     /*
  152.      * Find the end of the element (either a space or a close brace or
  153.      * the end of the string).
  154.      */
  155.  
  156.     while (1) {
  157.     switch (*p) {
  158.  
  159.         /*
  160.          * Open brace: don't treat specially unless the element is
  161.          * in braces.  In this case, keep a nesting count.
  162.          */
  163.  
  164.         case '{':
  165.         if (openBraces != 0) {
  166.             openBraces++;
  167.         }
  168.         break;
  169.  
  170.         /*
  171.          * Close brace: if element is in braces, keep nesting
  172.          * count and quit when the last close brace is seen.
  173.          */
  174.  
  175.         case '}':
  176.         if (openBraces == 1) {
  177.             char *p2;
  178.  
  179.             size = p - list;
  180.             p++;
  181.             if ((isascii(*p) && isspace(*p)) || (*p == 0)) {
  182.             goto done;
  183.             }
  184.             for (p2 = p; (*p2 != 0) && (!isspace(*p2)) && (p2 < p+20);
  185.                 p2++) {
  186.             /* null body */
  187.             }
  188.             Tcl_ResetResult(interp);
  189.             sprintf(interp->result,
  190.                 "list element in braces followed by \"%.*s\" instead of space",
  191.                 p2-p, p);
  192.             return TCL_ERROR;
  193.         } else if (openBraces != 0) {
  194.             openBraces--;
  195.         }
  196.         break;
  197.  
  198.         /*
  199.          * Backslash:  skip over everything up to the end of the
  200.          * backslash sequence.
  201.          */
  202.  
  203.         case '\\': {
  204.         int size;
  205.  
  206.         (void) Tcl_Backslash(p, &size);
  207.         p += size - 1;
  208.         break;
  209.         }
  210.  
  211.         /*
  212.          * Space: ignore if element is in braces or quotes;  otherwise
  213.          * terminate element.
  214.          */
  215.  
  216.         case ' ':
  217.         case '\f':
  218.         case '\n':
  219.         case '\r':
  220.         case '\t':
  221.         case '\v':
  222.         if ((openBraces == 0) && !inQuotes) {
  223.             size = p - list;
  224.             goto done;
  225.         }
  226.         break;
  227.  
  228.         /*
  229.          * Double-quote:  if element is in quotes then terminate it.
  230.          */
  231.  
  232.         case '"':
  233.         if (inQuotes) {
  234.             char *p2;
  235.  
  236.             size = p-list;
  237.             p++;
  238.             if ((isascii(*p) && isspace(*p)) || (*p == 0)) {
  239.             goto done;
  240.             }
  241.             for (p2 = p; (*p2 != 0) && (!isspace(*p2)) && (p2 < p+20);
  242.                 p2++) {
  243.             /* null body */
  244.             }
  245.             Tcl_ResetResult(interp);
  246.             sprintf(interp->result,
  247.                 "list element in quotes followed by \"%.*s\" %s",
  248.                 p2-p, p, "instead of space");
  249.             return TCL_ERROR;
  250.         }
  251.         break;
  252.  
  253.         /*
  254.          * End of list:  terminate element.
  255.          */
  256.  
  257.         case 0:
  258.         if (openBraces != 0) {
  259.             Tcl_SetResult(interp, "unmatched open brace in list",
  260.                 TCL_STATIC);
  261.             return TCL_ERROR;
  262.         } else if (inQuotes) {
  263.             Tcl_SetResult(interp, "unmatched open quote in list",
  264.                 TCL_STATIC);
  265.             return TCL_ERROR;
  266.         }
  267.         size = p - list;
  268.         goto done;
  269.  
  270.     }
  271.     p++;
  272.     }
  273.  
  274.     done:
  275.     while (isascii(*p) && isspace(*p)) {
  276.     p++;
  277.     }
  278.     *elementPtr = list;
  279.     *nextPtr = p;
  280.     if (sizePtr != 0) {
  281.     *sizePtr = size;
  282.     }
  283.     return TCL_OK;
  284. }
  285.  
  286. /*
  287.  *----------------------------------------------------------------------
  288.  *
  289.  * TclCopyAndCollapse --
  290.  *
  291.  *    Copy a string and eliminate any backslashes that aren't in braces.
  292.  *
  293.  * Results:
  294.  *    There is no return value.  Count chars. get copied from src
  295.  *    to dst.  Along the way, if backslash sequences are found outside
  296.  *    braces, the backslashes are eliminated in the copy.
  297.  *    After scanning count chars. from source, a null character is
  298.  *    placed at the end of dst.
  299.  *
  300.  * Side effects:
  301.  *    None.
  302.  *
  303.  *----------------------------------------------------------------------
  304.  */
  305.  
  306. void
  307. TclCopyAndCollapse(count, src, dst)
  308.     int count;            /* Total number of characters to copy
  309.                  * from src. */
  310.     register char *src;        /* Copy from here... */
  311.     register char *dst;        /* ... to here. */
  312. {
  313.     register char c;
  314.     int numRead;
  315.  
  316.     for (c = *src; count > 0; src++, c = *src, count--) {
  317.     if (c == '\\') {
  318.         *dst = Tcl_Backslash(src, &numRead);
  319.         dst++;
  320.         src += numRead-1;
  321.         count -= numRead-1;
  322.     } else {
  323.         *dst = c;
  324.         dst++;
  325.     }
  326.     }
  327.     *dst = 0;
  328. }
  329.  
  330. /*
  331.  *----------------------------------------------------------------------
  332.  *
  333.  * Tcl_SplitList --
  334.  *
  335.  *    Splits a list up into its constituent fields.
  336.  *
  337.  * Results
  338.  *    The return value is normally TCL_OK, which means that
  339.  *    the list was successfully split up.  If TCL_ERROR is
  340.  *    returned, it means that "list" didn't have proper list
  341.  *    structure;  interp->result will contain a more detailed
  342.  *    error message.
  343.  *
  344.  *    *argvPtr will be filled in with the address of an array
  345.  *    whose elements point to the elements of list, in order.
  346.  *    *argcPtr will get filled in with the number of valid elements
  347.  *    in the array.  A single block of memory is dynamically allocated
  348.  *    to hold both the argv array and a copy of the list (with
  349.  *    backslashes and braces removed in the standard way).
  350.  *    The caller must eventually free this memory by calling free()
  351.  *    on *argvPtr.  Note:  *argvPtr and *argcPtr are only modified
  352.  *    if the procedure returns normally.
  353.  *
  354.  * Side effects:
  355.  *    Memory is allocated.
  356.  *
  357.  *----------------------------------------------------------------------
  358.  */
  359.  
  360. int
  361. Tcl_SplitList(interp, list, argcPtr, argvPtr)
  362.     Tcl_Interp *interp;        /* Interpreter to use for error reporting. */
  363.     char *list;            /* Pointer to string with list structure. */
  364.     int *argcPtr;        /* Pointer to location to fill in with
  365.                  * the number of elements in the list. */
  366.     char ***argvPtr;        /* Pointer to place to store pointer to array
  367.                  * of pointers to list elements. */
  368. {
  369.     char **argv;
  370.     register char *p;
  371.     int size, i, result, elSize, brace;
  372.     char *element;
  373.  
  374.     /*
  375.      * Figure out how much space to allocate.  There must be enough
  376.      * space for both the array of pointers and also for a copy of
  377.      * the list.  To estimate the number of pointers needed, count
  378.      * the number of space characters in the list.
  379.      */
  380.  
  381.     for (size = 1, p = list; *p != 0; p++) {
  382.     if (isspace(*p)) {
  383.         size++;
  384.     }
  385.     }
  386.     size++;            /* Leave space for final NULL pointer. */
  387.     argv = (char **) ckalloc((unsigned)
  388.         ((size * sizeof(char *)) + (p - list) + 1));
  389.     for (i = 0, p = ((char *) argv) + size*sizeof(char *);
  390.         *list != 0; i++) {
  391.     result = TclFindElement(interp, list, &element, &list, &elSize, &brace);
  392.     if (result != TCL_OK) {
  393.         ckfree((char *) argv);
  394.         return result;
  395.     }
  396.     if (*element == 0) {
  397.         break;
  398.     }
  399.     if (i >= size) {
  400.         ckfree((char *) argv);
  401.         Tcl_SetResult(interp, "internal error in Tcl_SplitList",
  402.             TCL_STATIC);
  403.         return TCL_ERROR;
  404.     }
  405.     argv[i] = p;
  406.     if (brace) {
  407.         strncpy(p, element, elSize);
  408.         p += elSize;
  409.         *p = 0;
  410.         p++;
  411.     } else {
  412.         TclCopyAndCollapse(elSize, element, p);
  413.         p += elSize+1;
  414.     }
  415.     }
  416.  
  417.     argv[i] = NULL;
  418.     *argvPtr = argv;
  419.     *argcPtr = i;
  420.     return TCL_OK;
  421. }
  422.  
  423. /*
  424.  *----------------------------------------------------------------------
  425.  *
  426.  * Tcl_ScanElement --
  427.  *
  428.  *    This procedure is a companion procedure to Tcl_ConvertElement.
  429.  *    It scans a string to see what needs to be done to it (e.g.
  430.  *    add backslashes or enclosing braces) to make the string into
  431.  *    a valid Tcl list element.
  432.  *
  433.  * Results:
  434.  *    The return value is an overestimate of the number of characters
  435.  *    that will be needed by Tcl_ConvertElement to produce a valid
  436.  *    list element from string.  The word at *flagPtr is filled in
  437.  *    with a value needed by Tcl_ConvertElement when doing the actual
  438.  *    conversion.
  439.  *
  440.  * Side effects:
  441.  *    None.
  442.  *
  443.  *----------------------------------------------------------------------
  444.  */
  445.  
  446. int
  447. Tcl_ScanElement(string, flagPtr)
  448.     char *string;        /* String to convert to Tcl list element. */
  449.     int *flagPtr;        /* Where to store information to guide
  450.                  * Tcl_ConvertElement. */
  451. {
  452.     int flags, nestingLevel;
  453.     register char *p;
  454.  
  455.     /*
  456.      * This procedure and Tcl_ConvertElement together do two things:
  457.      *
  458.      * 1. They produce a proper list, one that will yield back the
  459.      * argument strings when evaluated or when disassembled with
  460.      * Tcl_SplitList.  This is the most important thing.
  461.      * 
  462.      * 2. They try to produce legible output, which means minimizing the
  463.      * use of backslashes (using braces instead).  However, there are
  464.      * some situations where backslashes must be used (e.g. an element
  465.      * like "{abc": the leading brace will have to be backslashed.  For
  466.      * each element, one of three things must be done:
  467.      *
  468.      * (a) Use the element as-is (it doesn't contain anything special
  469.      * characters).  This is the most desirable option.
  470.      *
  471.      * (b) Enclose the element in braces, but leave the contents alone.
  472.      * This happens if the element contains embedded space, or if it
  473.      * contains characters with special interpretation ($, [, ;, or \),
  474.      * or if it starts with a brace or double-quote, or if there are
  475.      * no characters in the element.
  476.      *
  477.      * (c) Don't enclose the element in braces, but add backslashes to
  478.      * prevent special interpretation of special characters.  This is a
  479.      * last resort used when the argument would normally fall under case
  480.      * (b) but contains unmatched braces.  It also occurs if the last
  481.      * character of the argument is a backslash or if the element contains
  482.      * a backslash followed by newline.
  483.      *
  484.      * The procedure figures out how many bytes will be needed to store
  485.      * the result (actually, it overestimates).  It also collects information
  486.      * about the element in the form of a flags word.
  487.      */
  488.  
  489.     nestingLevel = 0;
  490.     flags = 0;
  491.     if (string == NULL) {
  492.     string = "";
  493.     }
  494.     p = string;
  495.     if ((*p == '{') || (*p == '"') || (*p == 0)) {
  496.     flags |= USE_BRACES;
  497.     }
  498.     for ( ; *p != 0; p++) {
  499.     switch (*p) {
  500.         case '{':
  501.         nestingLevel++;
  502.         break;
  503.         case '}':
  504.         nestingLevel--;
  505.         if (nestingLevel < 0) {
  506.             flags |= TCL_DONT_USE_BRACES|BRACES_UNMATCHED;
  507.         }
  508.         break;
  509.         case '[':
  510.         case '$':
  511.         case ';':
  512.         case ' ':
  513.         case '\f':
  514.         case '\n':
  515.         case '\r':
  516.         case '\t':
  517.         case '\v':
  518.         flags |= USE_BRACES;
  519.         break;
  520.         case '\\':
  521.         if ((p[1] == 0) || (p[1] == '\n')) {
  522.             flags = TCL_DONT_USE_BRACES;
  523.         } else {
  524.             int size;
  525.  
  526.             (void) Tcl_Backslash(p, &size);
  527.             p += size-1;
  528.             flags |= USE_BRACES;
  529.         }
  530.         break;
  531.     }
  532.     }
  533.     if (nestingLevel != 0) {
  534.     flags = TCL_DONT_USE_BRACES | BRACES_UNMATCHED;
  535.     }
  536.     *flagPtr = flags;
  537.  
  538.     /*
  539.      * Allow enough space to backslash every character plus leave
  540.      * two spaces for braces.
  541.      */
  542.  
  543.     return 2*(p-string) + 2;
  544. }
  545.  
  546. /*
  547.  *----------------------------------------------------------------------
  548.  *
  549.  * Tcl_ConvertElement --
  550.  *
  551.  *    This is a companion procedure to Tcl_ScanElement.  Given the
  552.  *    information produced by Tcl_ScanElement, this procedure converts
  553.  *    a string to a list element equal to that string.
  554.  *
  555.  * Results:
  556.  *    Information is copied to *dst in the form of a list element
  557.  *    identical to src (i.e. if Tcl_SplitList is applied to dst it
  558.  *    will produce a string identical to src).  The return value is
  559.  *    a count of the number of characters copied (not including the
  560.  *    terminating NULL character).
  561.  *
  562.  * Side effects:
  563.  *    None.
  564.  *
  565.  *----------------------------------------------------------------------
  566.  */
  567.  
  568. int
  569. Tcl_ConvertElement(src, dst, flags)
  570.     register char *src;        /* Source information for list element. */
  571.     char *dst;            /* Place to put list-ified element. */
  572.     int flags;            /* Flags produced by Tcl_ScanElement. */
  573. {
  574.     register char *p = dst;
  575.  
  576.     /*
  577.      * See the comment block at the beginning of the Tcl_ScanElement
  578.      * code for details of how this works.
  579.      */
  580.  
  581.     if (src == NULL) {
  582.     src = "";
  583.     }
  584.     if ((flags & USE_BRACES) && !(flags & TCL_DONT_USE_BRACES)) {
  585.     *p = '{';
  586.     p++;
  587.     for ( ; *src != 0; src++, p++) {
  588.         *p = *src;
  589.     }
  590.     *p = '}';
  591.     p++;
  592.     } else if (*src == 0) {
  593.     /*
  594.      * If string is empty but can't use braces, then use special
  595.      * backslash sequence that maps to empty string.
  596.      */
  597.  
  598.     p[0] = '\\';
  599.     p[1] = '0';
  600.     p += 2;
  601.     } else {
  602.     for (; *src != 0 ; src++) {
  603.         switch (*src) {
  604.         case ']':
  605.         case '[':
  606.         case '$':
  607.         case ';':
  608.         case ' ':
  609.         case '\\':
  610.         case '"':
  611.             *p = '\\';
  612.             p++;
  613.             break;
  614.         case '{':
  615.         case '}':
  616.             if (flags & BRACES_UNMATCHED) {
  617.             *p = '\\';
  618.             p++;
  619.             }
  620.             break;
  621.         case '\f':
  622.             *p = '\\';
  623.             p++;
  624.             *p = 'f';
  625.             p++;
  626.             continue;
  627.         case '\n':
  628.             *p = '\\';
  629.             p++;
  630.             *p = 'n';
  631.             p++;
  632.             continue;
  633.         case '\r':
  634.             *p = '\\';
  635.             p++;
  636.             *p = 'r';
  637.             p++;
  638.             continue;
  639.         case '\t':
  640.             *p = '\\';
  641.             p++;
  642.             *p = 't';
  643.             p++;
  644.             continue;
  645.         case '\v':
  646.             *p = '\\';
  647.             p++;
  648.             *p = 'v';
  649.             p++;
  650.             continue;
  651.         }
  652.         *p = *src;
  653.         p++;
  654.     }
  655.     }
  656.     *p = '\0';
  657.     return p-dst;
  658. }
  659.  
  660. /*
  661.  *----------------------------------------------------------------------
  662.  *
  663.  * Tcl_Merge --
  664.  *
  665.  *    Given a collection of strings, merge them together into a
  666.  *    single string that has proper Tcl list structured (i.e.
  667.  *    Tcl_SplitList may be used to retrieve strings equal to the
  668.  *    original elements, and Tcl_Eval will parse the string back
  669.  *    into its original elements).
  670.  *
  671.  * Results:
  672.  *    The return value is the address of a dynamically-allocated
  673.  *    string containing the merged list.
  674.  *
  675.  * Side effects:
  676.  *    None.
  677.  *
  678.  *----------------------------------------------------------------------
  679.  */
  680.  
  681. char *
  682. Tcl_Merge(argc, argv)
  683.     int argc;            /* How many strings to merge. */
  684.     char **argv;        /* Array of string values. */
  685. {
  686. #   define LOCAL_SIZE 20
  687.     int localFlags[LOCAL_SIZE], *flagPtr;
  688.     int numChars;
  689.     char *result;
  690.     register char *dst;
  691.     int i;
  692.  
  693.     /*
  694.      * Pass 1: estimate space, gather flags.
  695.      */
  696.  
  697.     if (argc <= LOCAL_SIZE) {
  698.     flagPtr = localFlags;
  699.     } else {
  700.     flagPtr = (int *) ckalloc((unsigned) argc*sizeof(int));
  701.     }
  702.     numChars = 1;
  703.     for (i = 0; i < argc; i++) {
  704.     numChars += Tcl_ScanElement(argv[i], &flagPtr[i]) + 1;
  705.     }
  706.  
  707.     /*
  708.      * Pass two: copy into the result area.
  709.      */
  710.  
  711.     result = (char *) ckalloc((unsigned) numChars);
  712.     dst = result;
  713.     for (i = 0; i < argc; i++) {
  714.     numChars = Tcl_ConvertElement(argv[i], dst, flagPtr[i]);
  715.     dst += numChars;
  716.     *dst = ' ';
  717.     dst++;
  718.     }
  719.     if (dst == result) {
  720.     *dst = 0;
  721.     } else {
  722.     dst[-1] = 0;
  723.     }
  724.  
  725.     if (flagPtr != localFlags) {
  726.     ckfree((char *) flagPtr);
  727.     }
  728.     return result;
  729. }
  730.  
  731. /*
  732.  *----------------------------------------------------------------------
  733.  *
  734.  * Tcl_Concat --
  735.  *
  736.  *    Concatenate a set of strings into a single large string.
  737.  *
  738.  * Results:
  739.  *    The return value is dynamically-allocated string containing
  740.  *    a concatenation of all the strings in argv, with spaces between
  741.  *    the original argv elements.
  742.  *
  743.  * Side effects:
  744.  *    Memory is allocated for the result;  the caller is responsible
  745.  *    for freeing the memory.
  746.  *
  747.  *----------------------------------------------------------------------
  748.  */
  749.  
  750. char *
  751. Tcl_Concat(argc, argv)
  752.     int argc;            /* Number of strings to concatenate. */
  753.     char **argv;        /* Array of strings to concatenate. */
  754. {
  755.     int totalSize, i;
  756.     register char *p;
  757.     char *result;
  758.  
  759.     for (totalSize = 1, i = 0; i < argc; i++) {
  760.     totalSize += strlen(argv[i]) + 1;
  761.     }
  762.     result = (char *) ckalloc((unsigned) totalSize);
  763.     if (argc == 0) {
  764.     *result = '\0';
  765.     return result;
  766.     }
  767.     for (p = result, i = 0; i < argc; i++) {
  768.     char *element;
  769.     int length;
  770.  
  771.     /*
  772.      * Clip white space off the front and back of the string
  773.      * to generate a neater result, and ignore any empty
  774.      * elements.
  775.      */
  776.  
  777.     element = argv[i];
  778.     while (isspace(*element)) {
  779.         element++;
  780.     }
  781.     for (length = strlen(element);
  782.         (length > 0) && (isspace(element[length-1]));
  783.         length--) {
  784.         /* Null loop body. */
  785.     }
  786.     if (length == 0) {
  787.         continue;
  788.     }
  789.     (void) strncpy(p, element, length);
  790.     p += length;
  791.     *p = ' ';
  792.     p++;
  793.     }
  794.     if (p != result) {
  795.     p[-1] = 0;
  796.     } else {
  797.     *p = 0;
  798.     }
  799.     return result;
  800. }
  801.  
  802. /*
  803.  *----------------------------------------------------------------------
  804.  *
  805.  * Tcl_StringMatch --
  806.  *
  807.  *    See if a particular string matches a particular pattern.
  808.  *
  809.  * Results:
  810.  *    The return value is 1 if string matches pattern, and
  811.  *    0 otherwise.  The matching operation permits the following
  812.  *    special characters in the pattern: *?\[] (see the manual
  813.  *    entry for details on what these mean).
  814.  *
  815.  * Side effects:
  816.  *    None.
  817.  *
  818.  *----------------------------------------------------------------------
  819.  */
  820.  
  821. int
  822. Tcl_StringMatch(string, pattern)
  823.     register char *string;    /* String. */
  824.     register char *pattern;    /* Pattern, which may contain
  825.                  * special characters. */
  826. {
  827.     char c2;
  828.  
  829.     while (1) {
  830.     /* See if we're at the end of both the pattern and the string.
  831.      * If so, we succeeded.  If we're at the end of the pattern
  832.      * but not at the end of the string, we failed.
  833.      */
  834.     
  835.     if (*pattern == 0) {
  836.         if (*string == 0) {
  837.         return 1;
  838.         } else {
  839.         return 0;
  840.         }
  841.     }
  842.     if ((*string == 0) && (*pattern != '*')) {
  843.         return 0;
  844.     }
  845.  
  846.     /* Check for a "*" as the next pattern character.  It matches
  847.      * any substring.  We handle this by calling ourselves
  848.      * recursively for each postfix of string, until either we
  849.      * match or we reach the end of the string.
  850.      */
  851.     
  852.     if (*pattern == '*') {
  853.         pattern += 1;
  854.         if (*pattern == 0) {
  855.         return 1;
  856.         }
  857.         while (1) {
  858.         if (Tcl_StringMatch(string, pattern)) {
  859.             return 1;
  860.         }
  861.         if (*string == 0) {
  862.             return 0;
  863.         }
  864.         string += 1;
  865.         }
  866.     }
  867.     
  868.     /* Check for a "?" as the next pattern character.  It matches
  869.      * any single character.
  870.      */
  871.  
  872.     if (*pattern == '?') {
  873.         goto thisCharOK;
  874.     }
  875.  
  876.     /* Check for a "[" as the next pattern character.  It is followed
  877.      * by a list of characters that are acceptable, or by a range
  878.      * (two characters separated by "-").
  879.      */
  880.     
  881.     if (*pattern == '[') {
  882.         pattern += 1;
  883.         while (1) {
  884.         if ((*pattern == ']') || (*pattern == 0)) {
  885.             return 0;
  886.         }
  887.         if (*pattern == *string) {
  888.             break;
  889.         }
  890.         if (pattern[1] == '-') {
  891.             c2 = pattern[2];
  892.             if (c2 == 0) {
  893.             return 0;
  894.             }
  895.             if ((*pattern <= *string) && (c2 >= *string)) {
  896.             break;
  897.             }
  898.             if ((*pattern >= *string) && (c2 <= *string)) {
  899.             break;
  900.             }
  901.             pattern += 2;
  902.         }
  903.         pattern += 1;
  904.         }
  905.         while ((*pattern != ']') && (*pattern != 0)) {
  906.         pattern += 1;
  907.         }
  908.         goto thisCharOK;
  909.     }
  910.     
  911.     /* If the next pattern character is '/', just strip off the '/'
  912.      * so we do exact matching on the character that follows.
  913.      */
  914.     
  915.     if (*pattern == '\\') {
  916.         pattern += 1;
  917.         if (*pattern == 0) {
  918.         return 0;
  919.         }
  920.     }
  921.  
  922.     /* There's no special character.  Just make sure that the next
  923.      * characters of each string match.
  924.      */
  925.     
  926.     if (*pattern != *string) {
  927.         return 0;
  928.     }
  929.  
  930.     thisCharOK: pattern += 1;
  931.     string += 1;
  932.     }
  933. }
  934.  
  935. /*
  936.  *----------------------------------------------------------------------
  937.  *
  938.  * Tcl_SetResult --
  939.  *
  940.  *    Arrange for "string" to be the Tcl return value.
  941.  *
  942.  * Results:
  943.  *    None.
  944.  *
  945.  * Side effects:
  946.  *    interp->result is left pointing either to "string" (if "copy" is 0)
  947.  *    or to a copy of string.
  948.  *
  949.  *----------------------------------------------------------------------
  950.  */
  951.  
  952. void
  953. Tcl_SetResult(interp, string, freeProc)
  954.     Tcl_Interp *interp;        /* Interpreter with which to associate the
  955.                  * return value. */
  956.     char *string;        /* Value to be returned.  If NULL,
  957.                  * the result is set to an empty string. */
  958.     Tcl_FreeProc *freeProc;    /* Gives information about the string:
  959.                  * TCL_STATIC, TCL_VOLATILE, or the address
  960.                  * of a Tcl_FreeProc such as free. */
  961. {
  962.     register Interp *iPtr = (Interp *) interp;
  963.     int length;
  964.     Tcl_FreeProc *oldFreeProc = iPtr->freeProc;
  965.     char *oldResult = iPtr->result;
  966.  
  967.     iPtr->freeProc = freeProc;
  968.     if (string == NULL) {
  969.     iPtr->resultSpace[0] = 0;
  970.     iPtr->result = iPtr->resultSpace;
  971.     iPtr->freeProc = 0;
  972.     } else if (freeProc == TCL_VOLATILE) {
  973.     length = strlen(string);
  974.     if (length > TCL_RESULT_SIZE) {
  975.         iPtr->result = (char *) ckalloc((unsigned) length+1);
  976.         iPtr->freeProc = (Tcl_FreeProc *) free;
  977.     } else {
  978.         iPtr->result = iPtr->resultSpace;
  979.         iPtr->freeProc = 0;
  980.     }
  981.     strcpy(iPtr->result, string);
  982.     } else {
  983.     iPtr->result = string;
  984.     }
  985.  
  986.     /*
  987.      * If the old result was dynamically-allocated, free it up.  Do it
  988.      * here, rather than at the beginning, in case the new result value
  989.      * was part of the old result value.
  990.      */
  991.  
  992.     if (oldFreeProc != 0) {
  993.     if (oldFreeProc == (Tcl_FreeProc *) free) {
  994.         ckfree(oldResult);
  995.     } else {
  996.         (*oldFreeProc)(oldResult);
  997.     }
  998.     }
  999. }
  1000.  
  1001. /*
  1002.  *----------------------------------------------------------------------
  1003.  *
  1004.  * Tcl_AppendResult --
  1005.  *
  1006.  *    Append a variable number of strings onto the result already
  1007.  *    present for an interpreter.
  1008.  *
  1009.  * Results:
  1010.  *    None.
  1011.  *
  1012.  * Side effects:
  1013.  *    The result in the interpreter given by the first argument
  1014.  *    is extended by the strings given by the second and following
  1015.  *    arguments (up to a terminating NULL argument).
  1016.  *
  1017.  *----------------------------------------------------------------------
  1018.  */
  1019.  
  1020.     /* VARARGS2 */
  1021. #ifndef lint
  1022. void
  1023. Tcl_AppendResult(va_alist)
  1024. #else
  1025. void
  1026.     /* VARARGS2 */ /* ARGSUSED */
  1027. Tcl_AppendResult(interp, p, va_alist)
  1028.     Tcl_Interp *interp;        /* Interpreter whose result is to be
  1029.                  * extended. */
  1030.     char *p;            /* One or more strings to add to the
  1031.                  * result, terminated with NULL. */
  1032. #endif
  1033.     va_dcl
  1034. {
  1035.     va_list argList;
  1036.     register Interp *iPtr;
  1037.     char *string;
  1038.     int newSpace;
  1039.  
  1040.     /*
  1041.      * First, scan through all the arguments to see how much space is
  1042.      * needed.
  1043.      */
  1044.  
  1045.     va_start(argList);
  1046.     iPtr = va_arg(argList, Interp *);
  1047.     newSpace = 0;
  1048.     while (1) {
  1049.     string = va_arg(argList, char *);
  1050.     if (string == NULL) {
  1051.         break;
  1052.     }
  1053.     newSpace += strlen(string);
  1054.     }
  1055.     va_end(argList);
  1056.  
  1057.     /*
  1058.      * If the append buffer isn't already setup and large enough
  1059.      * to hold the new data, set it up.
  1060.      */
  1061.  
  1062.     if ((iPtr->result != iPtr->appendResult)
  1063.        || ((newSpace + iPtr->appendUsed) >= iPtr->appendAvl)) {
  1064.        SetupAppendBuffer(iPtr, newSpace);
  1065.     }
  1066.  
  1067.     /*
  1068.      * Final step:  go through all the argument strings again, copying
  1069.      * them into the buffer.
  1070.      */
  1071.  
  1072.     va_start(argList);
  1073.     (void) va_arg(argList, Tcl_Interp *);
  1074.     while (1) {
  1075.     string = va_arg(argList, char *);
  1076.     if (string == NULL) {
  1077.         break;
  1078.     }
  1079.     strcpy(iPtr->appendResult + iPtr->appendUsed, string);
  1080.     iPtr->appendUsed += strlen(string);
  1081.     }
  1082.     va_end(argList);
  1083. }
  1084.  
  1085. /*
  1086.  *----------------------------------------------------------------------
  1087.  *
  1088.  * Tcl_AppendElement --
  1089.  *
  1090.  *    Convert a string to a valid Tcl list element and append it
  1091.  *    to the current result (which is ostensibly a list).
  1092.  *
  1093.  * Results:
  1094.  *    None.
  1095.  *
  1096.  * Side effects:
  1097.  *    The result in the interpreter given by the first argument
  1098.  *    is extended with a list element converted from string.  A
  1099.  *    separator space is added before the converted list element
  1100.  *    unless the current result is empty, contains the single
  1101.  *    character "{", or ends in " {".
  1102.  *
  1103.  *----------------------------------------------------------------------
  1104.  */
  1105.  
  1106. void
  1107. Tcl_AppendElement(interp, string)
  1108.     Tcl_Interp *interp;        /* Interpreter whose result is to be
  1109.                  * extended. */
  1110.     char *string;        /* String to convert to list element and
  1111.                  * add to result. */
  1112. {
  1113.     register Interp *iPtr = (Interp *) interp;
  1114.     int size, flags;
  1115.     char *dst;
  1116.  
  1117.     /*
  1118.      * See how much space is needed, and grow the append buffer if
  1119.      * needed to accommodate the list element.
  1120.      */
  1121.  
  1122.     size = Tcl_ScanElement(string, &flags) + 1;
  1123.     if ((iPtr->result != iPtr->appendResult)
  1124.        || ((size + iPtr->appendUsed) >= iPtr->appendAvl)) {
  1125.        SetupAppendBuffer(iPtr, size+iPtr->appendUsed);
  1126.     }
  1127.  
  1128.     /*
  1129.      * Convert the string into a list element and copy it to the
  1130.      * buffer that's forming.
  1131.      */
  1132.  
  1133.     dst = iPtr->appendResult + iPtr->appendUsed;
  1134.     if ((iPtr->appendUsed > 0) && ((dst[-1] != '{')
  1135.         || ((iPtr->appendUsed > 1) && (dst[-2] != ' ')))) {
  1136.     iPtr->appendUsed++;
  1137.     *dst = ' ';
  1138.     dst++;
  1139.     }
  1140.     iPtr->appendUsed += Tcl_ConvertElement(string, dst, flags);
  1141. }
  1142.  
  1143. /*
  1144.  *----------------------------------------------------------------------
  1145.  *
  1146.  * SetupAppendBuffer --
  1147.  *
  1148.  *    This procedure makes sure that there is an append buffer
  1149.  *    properly initialized for interp, and that it has at least
  1150.  *    enough room to accommodate newSpace new bytes of information.
  1151.  *
  1152.  * Results:
  1153.  *    None.
  1154.  *
  1155.  * Side effects:
  1156.  *    None.
  1157.  *
  1158.  *----------------------------------------------------------------------
  1159.  */
  1160.  
  1161. static void
  1162. SetupAppendBuffer(iPtr, newSpace)
  1163.     register Interp *iPtr;    /* Interpreter whose result is being set up. */
  1164.     int newSpace;        /* Make sure that at least this many bytes
  1165.                  * of new information may be added. */
  1166. {
  1167.     int totalSpace;
  1168.  
  1169.     /*
  1170.      * Make the append buffer larger, if that's necessary, then
  1171.      * copy the current result into the append buffer and make the
  1172.      * append buffer the official Tcl result.
  1173.      */
  1174.  
  1175.     if (iPtr->result != iPtr->appendResult) {
  1176.     /*
  1177.      * If an oversized buffer was used recently, then free it up
  1178.      * so we go back to a smaller buffer.  This avoids tying up
  1179.      * memory forever after a large operation.
  1180.      */
  1181.  
  1182.     if (iPtr->appendAvl > 500) {
  1183.         ckfree(iPtr->appendResult);
  1184.         iPtr->appendResult = NULL;
  1185.         iPtr->appendAvl = 0;
  1186.     }
  1187.     iPtr->appendUsed = strlen(iPtr->result);
  1188.     }
  1189.     totalSpace = newSpace + iPtr->appendUsed;
  1190.     if (totalSpace >= iPtr->appendAvl) {
  1191.     char *new;
  1192.  
  1193.     if (totalSpace < 100) {
  1194.         totalSpace = 200;
  1195.     } else {
  1196.         totalSpace *= 2;
  1197.     }
  1198.     new = (char *) ckalloc((unsigned) totalSpace);
  1199.     strcpy(new, iPtr->result);
  1200.     if (iPtr->appendResult != NULL) {
  1201.         ckfree(iPtr->appendResult);
  1202.     }
  1203.     iPtr->appendResult = new;
  1204.     iPtr->appendAvl = totalSpace;
  1205.     } else if (iPtr->result != iPtr->appendResult) {
  1206.     strcpy(iPtr->appendResult, iPtr->result);
  1207.     }
  1208.     Tcl_FreeResult(iPtr);
  1209.     iPtr->result = iPtr->appendResult;
  1210. }
  1211.  
  1212. /*
  1213.  *----------------------------------------------------------------------
  1214.  *
  1215.  * Tcl_ResetResult --
  1216.  *
  1217.  *    This procedure restores the result area for an interpreter
  1218.  *    to its default initialized state, freeing up any memory that
  1219.  *    may have been allocated for the result and clearing any
  1220.  *    error information for the interpreter.
  1221.  *
  1222.  * Results:
  1223.  *    None.
  1224.  *
  1225.  * Side effects:
  1226.  *    None.
  1227.  *
  1228.  *----------------------------------------------------------------------
  1229.  */
  1230.  
  1231. void
  1232. Tcl_ResetResult(interp)
  1233.     Tcl_Interp *interp;        /* Interpreter for which to clear result. */
  1234. {
  1235.     register Interp *iPtr = (Interp *) interp;
  1236.  
  1237.     Tcl_FreeResult(iPtr);
  1238.     iPtr->result = iPtr->resultSpace;
  1239.     iPtr->resultSpace[0] = 0;
  1240.     iPtr->flags &=
  1241.         ~(ERR_ALREADY_LOGGED | ERR_IN_PROGRESS | ERROR_CODE_SET);
  1242. }
  1243.  
  1244. /*
  1245.  *----------------------------------------------------------------------
  1246.  *
  1247.  * Tcl_SetErrorCode --
  1248.  *
  1249.  *    This procedure is called to record machine-readable information
  1250.  *    about an error that is about to be returned.
  1251.  *
  1252.  * Results:
  1253.  *    None.
  1254.  *
  1255.  * Side effects:
  1256.  *    The errorCode global variable is modified to hold all of the
  1257.  *    arguments to this procedure, in a list form with each argument
  1258.  *    becoming one element of the list.  A flag is set internally
  1259.  *    to remember that errorCode has been set, so the variable doesn't
  1260.  *    get set automatically when the error is returned.
  1261.  *
  1262.  *----------------------------------------------------------------------
  1263.  */
  1264.     /* VARARGS2 */
  1265. #ifndef lint
  1266. void
  1267. Tcl_SetErrorCode(va_alist)
  1268. #else
  1269. void
  1270.     /* VARARGS2 */ /* ARGSUSED */
  1271. Tcl_SetErrorCode(interp, p, va_alist)
  1272.     Tcl_Interp *interp;        /* Interpreter whose errorCode variable is
  1273.                  * to be set. */
  1274.     char *p;            /* One or more elements to add to errorCode,
  1275.                  * terminated with NULL. */
  1276. #endif
  1277.     va_dcl
  1278. {
  1279.     va_list argList;
  1280.     char *string;
  1281.     int flags;
  1282.     Interp *iPtr;
  1283.  
  1284.     /*
  1285.      * Scan through the arguments one at a time, appending them to
  1286.      * $errorCode as list elements.
  1287.      */
  1288.  
  1289.     va_start(argList);
  1290.     iPtr = va_arg(argList, Interp *);
  1291.     flags = TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT;
  1292.     while (1) {
  1293.     string = va_arg(argList, char *);
  1294.     if (string == NULL) {
  1295.         break;
  1296.     }
  1297.     (void) Tcl_SetVar2((Tcl_Interp *) iPtr, "errorCode",
  1298.         (char *) NULL, string, flags);
  1299.     flags |= TCL_APPEND_VALUE;
  1300.     }
  1301.     va_end(argList);
  1302.     iPtr->flags |= ERROR_CODE_SET;
  1303. }
  1304.  
  1305. /*
  1306.  *----------------------------------------------------------------------
  1307.  *
  1308.  * TclGetListIndex --
  1309.  *
  1310.  *    Parse a list index, which may be either an integer or the
  1311.  *    value "end".
  1312.  *
  1313.  * Results:
  1314.  *    The return value is either TCL_OK or TCL_ERROR.  If it is
  1315.  *    TCL_OK, then the index corresponding to string is left in
  1316.  *    *indexPtr.  If the return value is TCL_ERROR, then string
  1317.  *    was bogus;  an error message is returned in interp->result.
  1318.  *    If a negative index is specified, it is rounded up to 0.
  1319.  *    The index value may be larger than the size of the list
  1320.  *    (this happens when "end" is specified).
  1321.  *
  1322.  * Side effects:
  1323.  *    None.
  1324.  *
  1325.  *----------------------------------------------------------------------
  1326.  */
  1327.  
  1328. int
  1329. TclGetListIndex(interp, string, indexPtr)
  1330.     Tcl_Interp *interp;            /* Interpreter for error reporting. */
  1331.     char *string;            /* String containing list index. */
  1332.     int *indexPtr;            /* Where to store index. */
  1333. {
  1334.     if (isdigit(*string) || (*string == '-')) {
  1335.     if (Tcl_GetInt(interp, string, indexPtr) != TCL_OK) {
  1336.         return TCL_ERROR;
  1337.     }
  1338.     if (*indexPtr < 0) {
  1339.         *indexPtr = 0;
  1340.     }
  1341.     } else if (strncmp(string, "end", strlen(string)) == 0) {
  1342.     *indexPtr = 1<<30;
  1343.     } else {
  1344.     Tcl_AppendResult(interp, "bad index \"", string,
  1345.         "\": must be integer or \"end\"", (char *) NULL);
  1346.     return TCL_ERROR;
  1347.     }
  1348.     return TCL_OK;
  1349. }
  1350.  
  1351. /*
  1352.  *----------------------------------------------------------------------
  1353.  *
  1354.  * TclCompileRegexp --
  1355.  *
  1356.  *    Compile a regular expression into a form suitable for fast
  1357.  *    matching.  This procedure retains a small cache of pre-compiled
  1358.  *    regular expressions in the interpreter, in order to avoid
  1359.  *    compilation costs as much as possible.
  1360.  *
  1361.  * Results:
  1362.  *    The return value is a pointer to the compiled form of string,
  1363.  *    suitable for passing to regexec.  If an error occurred while
  1364.  *    compiling the pattern, then NULL is returned and an error
  1365.  *    message is left in interp->result.
  1366.  *
  1367.  * Side effects:
  1368.  *    The cache of compiled regexp's in interp will be modified to
  1369.  *    hold information for string, if such information isn't already
  1370.  *    present in the cache.
  1371.  *
  1372.  *----------------------------------------------------------------------
  1373.  */
  1374.  
  1375. regexp *
  1376. TclCompileRegexp(interp, string)
  1377.     Tcl_Interp *interp;            /* For use in error reporting. */
  1378.     char *string;            /* String for which to produce
  1379.                      * compiled regular expression. */
  1380. {
  1381.     register Interp *iPtr = (Interp *) interp;
  1382.     int i, length;
  1383.     regexp *result;
  1384.  
  1385.     length = strlen(string);
  1386.     for (i = 0; i < NUM_REGEXPS; i++) {
  1387.     if ((length == iPtr->patLengths[i])
  1388.         && (strcmp(string, iPtr->patterns[i]) == 0)) {
  1389.         /*
  1390.          * Move the matched pattern to the first slot in the
  1391.          * cache and shift the other patterns down one position.
  1392.          */
  1393.  
  1394.         if (i != 0) {
  1395.         int j;
  1396.         char *cachedString;
  1397.  
  1398.         cachedString = iPtr->patterns[i];
  1399.         result = iPtr->regexps[i];
  1400.         for (j = i-1; j >= 0; j--) {
  1401.             iPtr->patterns[j+1] = iPtr->patterns[j];
  1402.             iPtr->patLengths[j+1] = iPtr->patLengths[j];
  1403.             iPtr->regexps[j+1] = iPtr->regexps[j];
  1404.         }
  1405.         iPtr->patterns[0] = cachedString;
  1406.         iPtr->patLengths[0] = length;
  1407.         iPtr->regexps[0] = result;
  1408.         }
  1409.         return iPtr->regexps[0];
  1410.     }
  1411.     }
  1412.  
  1413.     /*
  1414.      * No match in the cache.  Compile the string and add it to the
  1415.      * cache.
  1416.      */
  1417.  
  1418.     tclRegexpError = NULL;
  1419.     result = regcomp(string);
  1420.     if (tclRegexpError != NULL) {
  1421.     Tcl_AppendResult(interp,
  1422.         "couldn't compile regular expression pattern: ",
  1423.         tclRegexpError, (char *) NULL);
  1424.     return NULL;
  1425.     }
  1426.     if (iPtr->patterns[NUM_REGEXPS-1] != NULL) {
  1427.     ckfree(iPtr->patterns[NUM_REGEXPS-1]);
  1428.     ckfree((char *) iPtr->regexps[NUM_REGEXPS-1]);
  1429.     }
  1430.     for (i = NUM_REGEXPS - 2; i >= 0; i--) {
  1431.     iPtr->patterns[i+1] = iPtr->patterns[i];
  1432.     iPtr->patLengths[i+1] = iPtr->patLengths[i];
  1433.     iPtr->regexps[i+1] = iPtr->regexps[i];
  1434.     }
  1435.     iPtr->patterns[0] = (char *) ckalloc((unsigned) (length+1));
  1436.     strcpy(iPtr->patterns[0], string);
  1437.     iPtr->patLengths[0] = length;
  1438.     iPtr->regexps[0] = result;
  1439.     return result;
  1440. }
  1441.  
  1442. /*
  1443.  *----------------------------------------------------------------------
  1444.  *
  1445.  * regerror --
  1446.  *
  1447.  *    This procedure is invoked by the Henry Spencer's regexp code
  1448.  *    when an error occurs.  It saves the error message so it can
  1449.  *    be seen by the code that called Spencer's code.
  1450.  *
  1451.  * Results:
  1452.  *    None.
  1453.  *
  1454.  * Side effects:
  1455.  *    The value of "string" is saved in "tclRegexpError".
  1456.  *
  1457.  *----------------------------------------------------------------------
  1458.  */
  1459.  
  1460. void
  1461. regerror(string)
  1462.     char *string;            /* Error message. */
  1463. {
  1464.     tclRegexpError = string;
  1465. }
  1466.  
  1467. /*
  1468.  *----------------------------------------------------------------------
  1469.  *
  1470.  * Tcl_RegExpMatch --
  1471.  *
  1472.  *    See if a string matches a regular expression.
  1473.  *
  1474.  * Results:
  1475.  *    If an error occurs during the matching operation then -1
  1476.  *    is returned and interp->result contains an error message.
  1477.  *    Otherwise the return value is 1 if "string" matches "pattern"
  1478.  *    and 0 otherwise.
  1479.  *
  1480.  * Side effects:
  1481.  *    None.
  1482.  *
  1483.  *----------------------------------------------------------------------
  1484.  */
  1485.  
  1486. int
  1487. Tcl_RegExpMatch(interp, string, pattern)
  1488.     Tcl_Interp *interp;        /* Used for error reporting. */
  1489.     char *string;        /* String. */
  1490.     char *pattern;        /* Regular expression to match against
  1491.                  * string. */
  1492. {
  1493.     regexp *regexpPtr;
  1494.     int match;
  1495.  
  1496.     regexpPtr = TclCompileRegexp(interp, pattern);
  1497.     if (regexpPtr == NULL) {
  1498.     return -1;
  1499.     }
  1500.     tclRegexpError = NULL;
  1501.     match = regexec(regexpPtr, string, string);
  1502.     if (tclRegexpError != NULL) {
  1503.     Tcl_ResetResult(interp);
  1504.     Tcl_AppendResult(interp, "error while matching regular expression: ",
  1505.         tclRegexpError, (char *) NULL);
  1506.     return -1;
  1507.     }
  1508.     return match;
  1509. }
  1510.  
  1511. /*
  1512.  *----------------------------------------------------------------------
  1513.  *
  1514.  * Tcl_DStringInit --
  1515.  *
  1516.  *    Initializes a dynamic string, discarding any previous contents
  1517.  *    of the string (Tcl_DStringFree should have been called already
  1518.  *    if the dynamic string was previously in use).
  1519.  *
  1520.  * Results:
  1521.  *    None.
  1522.  *
  1523.  * Side effects:
  1524.  *    The dynamic string is initialized to be empty.
  1525.  *
  1526.  *----------------------------------------------------------------------
  1527.  */
  1528.  
  1529. void
  1530. Tcl_DStringInit(dsPtr)
  1531.     register Tcl_DString *dsPtr;    /* Pointer to structure for
  1532.                      * dynamic string. */
  1533. {
  1534.     dsPtr->string = dsPtr->staticSpace;
  1535.     dsPtr->length = 0;
  1536.     dsPtr->spaceAvl = TCL_DSTRING_STATIC_SIZE;
  1537.     dsPtr->staticSpace[0] = 0;
  1538. }
  1539.  
  1540. /*
  1541.  *----------------------------------------------------------------------
  1542.  *
  1543.  * Tcl_DStringAppend --
  1544.  *
  1545.  *    Append more characters to the current value of a dynamic string.
  1546.  *
  1547.  * Results:
  1548.  *    The return value is a pointer to the dynamic string's new value.
  1549.  *
  1550.  * Side effects:
  1551.  *    Length bytes from string (or all of string if length is less
  1552.  *    than zero) are added to the current value of the string.  Memory
  1553.  *    gets reallocated if needed to accomodate the string's new size.
  1554.  *
  1555.  *----------------------------------------------------------------------
  1556.  */
  1557.  
  1558. char *
  1559. Tcl_DStringAppend(dsPtr, string, length)
  1560.     register Tcl_DString *dsPtr;    /* Structure describing dynamic
  1561.                      * string. */
  1562.     char *string;            /* String to append.  If length is
  1563.                      * -1 then this must be
  1564.                      * null-terminated. */
  1565.     int length;                /* Number of characters from string
  1566.                      * to append.  If < 0, then append all
  1567.                      * of string, up to null at end. */
  1568. {
  1569.     int newSize;
  1570.     char *newString;
  1571.  
  1572.     if (length < 0) {
  1573.     length = strlen(string);
  1574.     }
  1575.     newSize = length + dsPtr->length;
  1576.  
  1577.     /*
  1578.      * Allocate a larger buffer for the string if the current one isn't
  1579.      * large enough.  Allocate extra space in the new buffer so that there
  1580.      * will be room to grow before we have to allocate again.
  1581.      */
  1582.  
  1583.     if (newSize >= dsPtr->spaceAvl) {
  1584.     dsPtr->spaceAvl = newSize*2;
  1585.     newString = (char *) ckalloc((unsigned) dsPtr->spaceAvl);
  1586.     strcpy(newString, dsPtr->string);
  1587.     if (dsPtr->string != dsPtr->staticSpace) {
  1588.         ckfree(dsPtr->string);
  1589.     }
  1590.     dsPtr->string = newString;
  1591.     }
  1592.  
  1593.     /*
  1594.      * Copy the new string into the buffer at the end of the old
  1595.      * one.
  1596.      */
  1597.  
  1598.     strncpy(dsPtr->string + dsPtr->length, string, length);
  1599.     dsPtr->length += length;
  1600.     dsPtr->string[dsPtr->length] = 0;
  1601.     return dsPtr->string;
  1602. }
  1603.  
  1604. /*
  1605.  *----------------------------------------------------------------------
  1606.  *
  1607.  * Tcl_DStringAppendElement --
  1608.  *
  1609.  *    Append a list element to the current value of a dynamic string.
  1610.  *
  1611.  * Results:
  1612.  *    The return value is a pointer to the dynamic string's new value.
  1613.  *
  1614.  * Side effects:
  1615.  *    String is reformatted as a list element and added to the current
  1616.  *    value of the string.  Memory gets reallocated if needed to
  1617.  *    accomodate the string's new size.
  1618.  *
  1619.  *----------------------------------------------------------------------
  1620.  */
  1621.  
  1622. char *
  1623. Tcl_DStringAppendElement(dsPtr, string)
  1624.     register Tcl_DString *dsPtr;    /* Structure describing dynamic
  1625.                      * string. */
  1626.     char *string;            /* String to append.  Must be
  1627.                      * null-terminated. */
  1628. {
  1629.     int newSize, flags;
  1630.     char *dst, *newString;
  1631.  
  1632.     newSize = Tcl_ScanElement(string, &flags) + dsPtr->length + 1;
  1633.  
  1634.     /*
  1635.      * Allocate a larger buffer for the string if the current one isn't
  1636.      * large enough.  Allocate extra space in the new buffer so that there
  1637.      * will be room to grow before we have to allocate again.
  1638.      */
  1639.  
  1640.     if (newSize >= dsPtr->spaceAvl) {
  1641.     dsPtr->spaceAvl = newSize*2;
  1642.     newString = (char *) ckalloc((unsigned) dsPtr->spaceAvl);
  1643.     strcpy(newString, dsPtr->string);
  1644.     if (dsPtr->string != dsPtr->staticSpace) {
  1645.         ckfree(dsPtr->string);
  1646.     }
  1647.     dsPtr->string = newString;
  1648.     }
  1649.  
  1650.     /*
  1651.      * Convert the new string to a list element and copy it into the
  1652.      * buffer at the end.  Add a space separator unles we're at the
  1653.      * start of the string or just after a " {".
  1654.      */
  1655.  
  1656.     dst = dsPtr->string + dsPtr->length;
  1657.     if ((dsPtr->length > 0) && ((dst[-1] != '{')
  1658.         || ((dsPtr->length > 1) && (dst[-2] != ' ')))) {
  1659.     *dst = ' ';
  1660.     dst++;
  1661.     dsPtr->length++;
  1662.     }
  1663.     dsPtr->length += Tcl_ConvertElement(string, dst, flags);
  1664.     return dsPtr->string;
  1665. }
  1666.  
  1667. /*
  1668.  *----------------------------------------------------------------------
  1669.  *
  1670.  * Tcl_DStringTrunc --
  1671.  *
  1672.  *    Truncate a dynamic string to a given length without freeing
  1673.  *    up its storage.
  1674.  *
  1675.  * Results:
  1676.  *    None.
  1677.  *
  1678.  * Side effects:
  1679.  *    The length of dsPtr is reduced to length unless it was already
  1680.  *    shorter than that.
  1681.  *
  1682.  *----------------------------------------------------------------------
  1683.  */
  1684.  
  1685. void
  1686. Tcl_DStringTrunc(dsPtr, length)
  1687.     register Tcl_DString *dsPtr;    /* Structure describing dynamic
  1688.                      * string. */
  1689.     int length;                /* New length for dynamic string. */
  1690. {
  1691.     if (length < 0) {
  1692.     length = 0;
  1693.     }
  1694.     if (length < dsPtr->length) {
  1695.     dsPtr->length = length;
  1696.     dsPtr->string[length] = 0;
  1697.     }
  1698. }
  1699.  
  1700. /*
  1701.  *----------------------------------------------------------------------
  1702.  *
  1703.  * Tcl_DStringFree --
  1704.  *
  1705.  *    Frees up any memory allocated for the dynamic string and
  1706.  *    reinitializes the string to an empty state.
  1707.  *
  1708.  * Results:
  1709.  *    None.
  1710.  *
  1711.  * Side effects:
  1712.  *    The previous contents of the dynamic string are lost, and
  1713.  *    the new value is an empty string.
  1714.  *
  1715.  *----------------------------------------------------------------------
  1716.  */
  1717.  
  1718. void
  1719. Tcl_DStringFree(dsPtr)
  1720.     register Tcl_DString *dsPtr;    /* Structure describing dynamic
  1721.                      * string. */
  1722. {
  1723.     if (dsPtr->string != dsPtr->staticSpace) {
  1724.     ckfree(dsPtr->string);
  1725.     }
  1726.     dsPtr->string = dsPtr->staticSpace;
  1727.     dsPtr->length = 0;
  1728.     dsPtr->spaceAvl = TCL_DSTRING_STATIC_SIZE;
  1729.     dsPtr->staticSpace[0] = 0;
  1730. }
  1731.  
  1732. /*
  1733.  *----------------------------------------------------------------------
  1734.  *
  1735.  * Tcl_DStringResult --
  1736.  *
  1737.  *    This procedure moves the value of a dynamic string into an
  1738.  *    interpreter as its result.  The string itself is reinitialized
  1739.  *    to an empty string.
  1740.  *
  1741.  * Results:
  1742.  *    None.
  1743.  *
  1744.  * Side effects:
  1745.  *    The string is "moved" to interp's result, and any existing
  1746.  *    result for interp is freed up.  DsPtr is reinitialized to
  1747.  *    an empty string.
  1748.  *
  1749.  *----------------------------------------------------------------------
  1750.  */
  1751.  
  1752. void
  1753. Tcl_DStringResult(interp, dsPtr)
  1754.     Tcl_Interp *interp;            /* Interpreter whose result is to be
  1755.                      * reset. */
  1756.     Tcl_DString *dsPtr;            /* Dynamic string that is to become
  1757.                      * the result of interp. */
  1758. {
  1759.     Tcl_FreeResult(interp);
  1760.     if (dsPtr->string != dsPtr->staticSpace) {
  1761.     interp->result = dsPtr->string;
  1762.     interp->freeProc = (Tcl_FreeProc *) free;
  1763.     } else if (dsPtr->length < TCL_RESULT_SIZE) {
  1764.     strcpy(interp->result, dsPtr->string);
  1765.     } else {
  1766.     Tcl_SetResult(interp, dsPtr->string, TCL_VOLATILE);
  1767.     }
  1768.     dsPtr->string = dsPtr->staticSpace;
  1769.     dsPtr->length = 0;
  1770.     dsPtr->spaceAvl = TCL_DSTRING_STATIC_SIZE;
  1771.     dsPtr->staticSpace[0] = 0;
  1772. }
  1773.  
  1774. /*
  1775.  *----------------------------------------------------------------------
  1776.  *
  1777.  * Tcl_PrintDouble --
  1778.  *
  1779.  *    Given a floating-point value, this procedure converts it to
  1780.  *    an ASCII string using.
  1781.  *
  1782.  * Results:
  1783.  *    The ASCII equivalent of "value" is written at "dst".  It is
  1784.  *    written using the current precision, and it is guaranteed to
  1785.  *    contain a decimal point or exponent, so that it looks like
  1786.  *    a floating-point value and not an integer.
  1787.  *
  1788.  * Side effects:
  1789.  *    None.
  1790.  *
  1791.  *----------------------------------------------------------------------
  1792.  */
  1793.  
  1794. void
  1795. Tcl_PrintDouble(interp, value, dst)
  1796.     Tcl_Interp *interp;            /* Interpreter whose tcl_precision
  1797.                      * variable controls printing. */
  1798.     double value;            /* Value to print as string. */
  1799.     char *dst;                /* Where to store converted value;
  1800.                      * must have at least TCL_DOUBLE_SPACE
  1801.                      * characters. */
  1802. {
  1803.     register char *p;
  1804.     sprintf(dst, ((Interp *) interp)->pdFormat, value);
  1805.  
  1806.     /*
  1807.      * If the ASCII result looks like an integer, add ".0" so that it
  1808.      * doesn't look like an integer anymore.  This prevents floating-point
  1809.      * values from being converted to integers unintentionally.
  1810.      */
  1811.  
  1812.     for (p = dst; *p != 0; p++) {
  1813.     if ((*p == '.') || (isalpha(*p))) {
  1814.         return;
  1815.     }
  1816.     }
  1817.     p[0] = '.';
  1818.     p[1] = '0';
  1819.     p[2] = 0;
  1820. }
  1821.  
  1822. /*
  1823.  *----------------------------------------------------------------------
  1824.  *
  1825.  * TclPrecTraceProc --
  1826.  *
  1827.  *    This procedure is invoked whenever the variable "tcl_precision"
  1828.  *    is written.
  1829.  *
  1830.  * Results:
  1831.  *    Returns NULL if all went well, or an error message if the
  1832.  *    new value for the variable doesn't make sense.
  1833.  *
  1834.  * Side effects:
  1835.  *    If the new value doesn't make sense then this procedure
  1836.  *    undoes the effect of the variable modification.  Otherwise
  1837.  *    it modifies the format string that's used by Tcl_PrintDouble.
  1838.  *
  1839.  *----------------------------------------------------------------------
  1840.  */
  1841.  
  1842.     /* ARGSUSED */
  1843. char *
  1844. TclPrecTraceProc(clientData, interp, name1, name2, flags)
  1845.     ClientData clientData;    /* Not used. */
  1846.     Tcl_Interp *interp;        /* Interpreter containing variable. */
  1847.     char *name1;        /* Name of variable. */
  1848.     char *name2;        /* Second part of variable name. */
  1849.     int flags;            /* Information about what happened. */
  1850. {
  1851.     register Interp *iPtr = (Interp *) interp;
  1852.     char *value, *end;
  1853.     int prec;
  1854.  
  1855.     /*
  1856.      * If the variable is unset, then recreate the trace and restore
  1857.      * the default value of the format string.
  1858.      */
  1859.  
  1860.     if (flags & TCL_TRACE_UNSETS) {
  1861.     if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) {
  1862.         Tcl_TraceVar2(interp, name1, name2,
  1863.             TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
  1864.             TclPrecTraceProc, clientData);
  1865.     }
  1866.     strcpy(iPtr->pdFormat, DEFAULT_PD_FORMAT);
  1867.     iPtr->pdPrec = DEFAULT_PD_PREC;
  1868.     return (char *) NULL;
  1869.     }
  1870.  
  1871.     value = Tcl_GetVar2(interp, name1, name2, flags & TCL_GLOBAL_ONLY);
  1872.     if (value == NULL) {
  1873.     value = "";
  1874.     }
  1875.     prec = strtoul(value, &end, 10);
  1876.     if ((prec <= 0) || (prec > TCL_MAX_PREC) || (prec > 100) ||
  1877.         (end == value) || (*end != 0)) {
  1878.     char oldValue[10];
  1879.  
  1880.     sprintf(oldValue, "%d", iPtr->pdPrec);
  1881.     Tcl_SetVar2(interp, name1, name2, oldValue, flags & TCL_GLOBAL_ONLY);
  1882.     return "improper value for precision";
  1883.     }
  1884.     sprintf(iPtr->pdFormat, "%%.%dg", prec);
  1885.     iPtr->pdPrec = prec;
  1886.     return (char *) NULL;
  1887. }
  1888.